var showPage = (function () {
    var pages = $$('.page_container .page'),
        nextIndex = null,
        pageIndex = 0; //当前显示页面的索引

    function setStaic() {
        nextIndex = null;
        for (var i = 0; i < pages.length; i++) {
            if (i == pageIndex) {
                pages[pageIndex].style.zIndex = 1
                pages[pageIndex].style.top = '0px'
            } else {
                pages[i].style.zIndex = 10
                pages[i].style.top = (i - pageIndex) * height() + 'px'
            }

        }
    }

    function moving(dis) {
        for (var i = 0; i < pages.length; i++) {
            if (i == pageIndex) {
                pages[pageIndex].style.top = '0px'
            } else {
                pages[i].style.top = (i - pageIndex) * height() + dis + 'px'
            }
        }
        if (dis < 0 && pageIndex < pages.length - 1) {
            nextIndex = pageIndex + 1
        } else if (dis > 0 && pageIndex > 0) {
            nextIndex = pageIndex - 1
        } else {
            nextIndex = null
        }
    }

    function finishMove() {
        if (nextIndex == null) {
            setStaic()
            return
        }
        var nextPage = pages[nextIndex]
        nextPage.style.top = '0px'
        nextPage.style.transition = '0.5s'
        setTimeout(() => {
            pageIndex = nextIndex
            nextPage.style.transition = ''
            setStaic()
        }, 500);

    }

    var pageContainer = $('.page_container')
    pageContainer.ontouchstart = function (e) {
        var y = e.changedTouches[0].clientY
        pageContainer.ontouchmove = function (e) {
            var dis = e.changedTouches[0].clientY - y
            if (Math.abs(dis) < 20) {
                dis = 0
            }
            moving(dis)
        }
        pageContainer.ontouchend = function (e) {
            finishMove()
            pageContainer.ontouchmove = null
        }
    }
    setStaic()

    function showPage(index) {
        var pageDom = pages[index]
        if (index < pageIndex) {
            pageDom.style.top = -height() + 'px'
        } else if (index > pageIndex) {
            pageDom.style.top = height() + 'px'
        } else {
            if (pageIndex == 0) {
                pageIndex++
            } else {
                pageIndex--
            }
            setStaic()
        }
        pageDom.clientHeight //读取dom的尺寸和位置可以让浏览器强行渲染
        nextIndex = index
        finishMove()
    }
    return showPage
})()